package com.shwread.android.ui.page;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.shwread.android.qysw.activity.BaseBusinessActivity;
import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw.activity.MessageActivity;
import com.shwread.android.qysw10000243.R;
import com.shwread.android.ui.dialog.GuideDialog;
import com.shwread.android.ui.dialog.NoNetDialog;
import com.shwread.android.ui.widget.InteractionContentView;
import com.shwread.android.ui.widget.InteractionContentView.InteractionContentViewListener;
import com.shwread.android.ui.widget.refresh.PullToRefreshScrollView;
import com.shwread.android.ui.widget.refresh.PullToRefreshUtil;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase.OnRefreshListener;
import com.shwread.httpsdk.http.callback.BaseAction;
import com.shwread.httpsdk.http.face.QryUnReadTotalAction;
import com.tgx.tina.android.ipc.framework.IUIPage;

import org.geometerplus.android.util.QyreaderPerferencesUtil;

import base.tina.core.task.infc.ITaskResult;
import logic.constants.DefaultConsts;
import logic.util.NetworkUtil;


/**
 * 互动中心页面
 * 
 * @author zouqp
 * @date 2015年3月3日
 */
public class InteractionCenterPage
        extends
        AbstractUIPage<MainActivity>
        implements
        OnClickListener
{
	private static InteractionCenterPage instance;
	private TextView                     tvTitle;
	private ImageView                       ivPersion;
	
	private View                         titleView;
	private PullToRefreshScrollView      contentView;
	
	//added by zouqp
	private LinearLayout                 ll_interaction_contentview;
	private InteractionContentView       contentItemView;
	private View                         messageLayout;
	private ImageView                    ivMsgUnread;
	
	public static InteractionCenterPage getInstance(MainActivity bActivity) {
		if (instance == null) {
			instance = new InteractionCenterPage(bActivity);
		} else {
			instance.setActivity(bActivity);
		}
		return instance;
	}
	
	public InteractionCenterPage(MainActivity t) {
		super(t);
	}
	
	@Override
	public <E extends Activity> View createView(E arg0, int arg1) {
		if (null != curMyView) return curMyView;
		curMyView = bActivity.getLayoutInflater().inflate(R.layout.interaction_center_layout, null);
		initView();
		setListener();
		initGuide();
		return curMyView;
	}
	
	@SuppressLint ("UseSparseArrays")
	void initView() {
		tvTitle = (TextView) curMyView.findViewById(R.id.common_header_name);
		tvTitle.setText("互动中心");
		ivPersion = (ImageView) curMyView.findViewById(R.id.common_header_persion);
		ivPersion.setVisibility(View.VISIBLE);
		messageLayout = curMyView.findViewById(R.id.common_header_msg_layout);
		messageLayout.setVisibility(View.VISIBLE);
		ivMsgUnread = (ImageView) curMyView.findViewById(R.id.common_header_msg_unread_flag);
		
		ll_interaction_contentview = (LinearLayout) curMyView.findViewById(R.id.ll_interaction_contentview);
		
		titleView = curMyView.findViewById(R.id.common_title_layout);
		
		contentView = (PullToRefreshScrollView) curMyView.findViewById(R.id.iteraction_center_view);
		
		PullToRefreshUtil.initLabel(context, contentView);
		
		//增加内容项视图
		contentItemView = new InteractionContentView(context);
		contentItemView.setBaseActivity(bActivity);
		contentItemView.setInteractionContentViewListener(new InteractionContentViewListener()
		{
			@Override
			public void OnLoadDataCompleted(int flag) {
				if (flag == 1)
				{ //首次装载
					contentView.onRefreshComplete();
				}
				else if (flag == 2)
				{//装载更多
					contentView.onRefreshComplete();
				}
			}
		});
		ll_interaction_contentview.addView(contentItemView);
	}
	
	void setListener() {
		messageLayout.setOnClickListener(this);
		ivPersion.setOnClickListener(this);
		titleView.setOnClickListener(this);
		
		contentView.setOnRefreshListener(new OnRefreshListener<ScrollView>()
		{
			@Override
			public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
				if (contentView.isHeaderShown())
				{ //下拉刷新
					refresh();
				}
				else if (contentView.isFooterShown())
				{ //上拉加载
					loadMore();
				}
			}
		});
	}
	
	/** 下拉刷新 */
	private void refresh() {
		//TODO
		contentItemView.getInteractionData(1);
	}
	
	/** 加载更多 */
	private void loadMore() {
		if (contentItemView.getDataSize() == 0)
		{
			PullToRefreshUtil.setLoadLabel(contentView, "没有更多数据了");
		}
		else
		{
			if (contentItemView.getHasMore())
			{
				//加载下一页
				contentItemView.getNextPage();
				return;
			}
			else if (contentItemView.isGotMaxSize())
			{
				//已经达到了最大条数，
				PullToRefreshUtil.setLoadLabel(contentView, "已经达到了最大条数");
			}
			else
			{
				//没有更多了， 所以不再加载下一页
				PullToRefreshUtil.setLoadLabel(contentView, "没有更多数据了");
			}
		}
		contentView.onRefreshComplete();
	}
	
	@Override
	public void dispose() {
		super.dispose();
	}
	
	@Override
	public int enter(IUIPage<?> arg0) {
		showGuide();
		if (NetworkUtil.isNetAvailable(bActivity))
		{
			contentItemView.getInteractionData(2);//初始装载
		}
		else
		{
			new NoNetDialog(bActivity).show();
		}
		qryUnReadTotal();
		return 0;
	}
	
	private void qryUnReadTotal() {
		new QryUnReadTotalAction(bActivity, DefaultConsts.TYPE_WRITESOURCE_ENTERPRISE, new GetUnreadAction(true)).start();
		new QryUnReadTotalAction(bActivity, DefaultConsts.TYPE_WRITESOURCE_SYSTEM, new GetUnreadAction(false)).start();
	}
	
	private Integer tempE = null, tempS = null;
	
	private class GetUnreadAction
	        extends
	        BaseAction
	{
		boolean flag;
		
		public GetUnreadAction(boolean flag) {
			this.flag = flag;
		}
		
		@Override
		public void OK(Object obj) {
			final int count = (Integer) obj;
			if (flag)
			{
				//			if(count>0) Const.UNREAD_MSG_COUNT_E = count;
				tempE = count;
			}
			else
			{
				//			if(count>0) Const.UNREAD_MSG_COUNT_S = count;
				tempS = count;
			}
			if (tempE != null && tempS != null)
			//			if (Const.UNREAD_MSG_COUNT_E != null && Const.UNREAD_MSG_COUNT_S != null)
			{
				bActivity.getUIHandler().post(new Runnable()
				{
					@Override
					public void run() {
						boolean res = (tempE == 0 && tempS == 0) ? false : true;
						//					boolean res = (Const.UNREAD_MSG_COUNT_E == 0 && Const.UNREAD_MSG_COUNT_S == 0) ? false : true;
						ivMsgUnread.setVisibility(res ? View.VISIBLE : View.GONE);
					}
				});
			}
		}
	}
	
	@Override
	public int leave(IUIPage<?> arg0) {
		return 0;
	}
	
	@Override
	public void notifyView(int arg0, Bundle arg1) {
		switch (arg0) {
			case DefaultConsts.PAGE_ONRESUME_CODE:
				contentItemView.getInteractionData(1);
				qryUnReadTotal();
				break;
			case DefaultConsts.MESSAGE_UNREAD_CHANGE_CODE:
				boolean res = arg1.getBoolean("result");
				ivMsgUnread.setVisibility(res ? View.VISIBLE : View.GONE);
				break;
			case BaseBusinessActivity.COMMENTS_REQUEST_CODE:
				contentItemView.updateTheCommentsCount();
				break;
		}
	}
	
	@Override
	public void setStatus(int arg0) {
		
	}
	
	@Override
	public View updateView(int arg0, ITaskResult arg1) {
		return null;
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.common_header_msg_layout:
				goMessagePage();
				break;
			case R.id.common_header_persion:
				bActivity.goPersonalActivity();
				break;
			case R.id.common_title_layout:
				titleDoubleClick();
				break;
		}
	}
	
	private void goMessagePage() {
		bActivity.startActivity(new Intent(bActivity, MessageActivity.class));
	}
	
	private int       clickCount;
	private long      preClickTime;
	/** 双击有效时间500毫秒 */
	private final int defalultValue = 500;
	
	/** 标题栏双击，回到顶部 */
	private void titleDoubleClick() {
		if (clickCount == 0)
		{
			preClickTime = System.currentTimeMillis();
			clickCount++;
		}
		else if (clickCount == 1)
		{
			if ((System.currentTimeMillis() - preClickTime) < defalultValue)
			{
				gotoTop();
			}
			clickCount = 0;
			preClickTime = 0;
		}
		else
		{
			clickCount = 0;
			preClickTime = 0;
		}
	}
	
	/** 回到顶部 */
	private void gotoTop() {
		contentItemView.post(new Runnable()
		{
			@Override
			public void run() {
				contentView.getRefreshableView().scrollTo(0, 0);
			}
		});
	}
	
	private GuideDialog             dialog;
	private boolean                 showHelp;
	private QyreaderPerferencesUtil util;
	
	private void initGuide() {
		util = QyreaderPerferencesUtil.getInstance(bActivity, DefaultConsts.FIRST_TAG);
		dialog = new GuideDialog(bActivity, R.layout.enterprise_page_firstin);
	}
	
	private void showGuide() {
		showHelp = util.getShowEnterpriseHelp();
		if (showHelp)
		{
			if (null != dialog && !dialog.isShowing())
			{
				dialog.show();
			}
			util.setShowEnterpriseHelp(false);
		}
	}
	
}
